package com.example.homework.ui

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import com.example.homework.R
import com.example.homework.adapters.FootLoadStateAdapter
import com.example.homework.adapters.PhotoPagedAdapter
import com.example.homework.databinding.FragmentMainBinding
import com.example.homework.ui.PhotoFragment.Companion.ARG_IMG_SRC
import com.example.homework.ui.PhotoFragment.Companion.ARG_IMG_TRANSITION
import com.example.homework.viewmodels.MainViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

class MainFragment : Fragment() {
    private var _binding: FragmentMainBinding? = null
    private val binding: FragmentMainBinding
        get() = _binding!!
    private val viewModel: MainViewModel by viewModels<MainViewModel>()
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        _binding = FragmentMainBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val adapter =
            PhotoPagedAdapter { imageView: View, imgSrc: String ->
                openImage(
                    imageView,
                    imgSrc
                )
            }
        binding.swipeRefresh.setOnRefreshListener {
            adapter.refresh()
        }
        adapter.loadStateFlow.onEach {
            binding.swipeRefresh.isRefreshing = it.refresh == LoadState.Loading
        }.launchIn(viewLifecycleOwner.lifecycleScope)
        binding.photosRecyclerView.adapter = adapter.withLoadStateFooter(FootLoadStateAdapter())
        binding.photosRecyclerView.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
            override fun onPreDraw(): Boolean {
                binding.photosRecyclerView.viewTreeObserver.removeOnPreDrawListener(this)
                startPostponedEnterTransition() // Resume transition when RecyclerView is ready
                return true
            }
        })
        lifecycleScope.launch {
            try {
                viewModel.pagedPhotos.onEach {
                    adapter.submitData(it)
                }.launchIn(viewLifecycleOwner.lifecycleScope)

            } catch (e: Exception) {
                Log.e("API_ERROR", "Error fetching photos: ${e.message}")
            }
        }
    }

    private fun openImage(imageView: View, imgSrc: String) {
        val extras = FragmentNavigatorExtras(
            imageView to imageView.transitionName
        )

        val bundle = Bundle().apply {
            putString(ARG_IMG_SRC, imgSrc)
            putString(ARG_IMG_TRANSITION, imageView.transitionName)
        }

        findNavController().navigate(
            R.id.action_mainFragment_to_photoFragment,
            bundle,
            null,
            extras
        )
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}